package com.cbwl.eoas.common.util.jpush;

import java.util.Date;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cbwl.eoas.common.framework.utils.JSONUtil;
import com.cbwl.eoas.common.util.constain.DicDetailConstant;
import com.cbwl.eoas.common.web.Result;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.PushPayload.Builder;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;


public class JPush {

    private static final String MESSAGE_TITLE = "EOAS";

    public static final String SALT = "EOAS";
    /*****************************生产环境消息推送配置开始***************************************/
//	private static final String USER_APPKEY = "95946a76565c798849a4c737";
//	private static final String USER_MASTERSECRET = "3aa0ecd83a6492f2ef782243";
//
//	private static final String BROKER_APPKEY = "32083e47dde410e0bbc37832";
//	private static final String BROKER_MASTERSECRET = "8e52c493df211e4248a8fd60";
    /********************************生产环境消息推送配置结束***********************************/

    /*****************************测试环境消息推送配置开始***************************************/
//	private static final String USER_APPKEY = "950f503b00f5b61205ffe74f";
//	private static final String USER_MASTERSECRET = "124a55306b68aaf5cf5be8a8";
//
//	private static final String BROKER_APPKEY = "ee2130972d8a3f8cd7e9a964";
//	private static final String BROKER_MASTERSECRET = "03f725d3dbe44d73bb0e9ffe";
    /********************************测试环境消息推送配置结束***********************************/

    /***********************************************************************************/
    private String userAppkey;
    private String userMastersecret;

    private JPushClient userClient;
    private static JPush jpush;

    /**
     * Get instance j push.
     *
     * @return the j push
     */
    public static JPush getInstance() {
        if (jpush == null) {
            jpush = new JPush();
        }
        return jpush;
    }

    /***********************************************************************************/

    private static final Logger logger = LoggerFactory.getLogger(JPush.class.getName());

//	public static JPushClient getUserJPushClient() {
//		return new JPushClient(USER_MASTERSECRET, USER_APPKEY);
//	}
//
//	public static JPushClient getBrokerJPushClient() {
//		return new JPushClient(BROKER_MASTERSECRET, BROKER_APPKEY);
//	}

    /**
     * 推送所有用户
     *
     * @param client  the client
     * @param content the content
     */
    public void pushAll(JPushClient client, String content) {
        try {
            Builder builder = PushPayload.newBuilder();
            builder.setPlatform(Platform.all());
            builder.setAudience(Audience.all());
            builder.setNotification(Notification
                    .newBuilder()
                    .addPlatformNotification(
                            AndroidNotification.newBuilder().setAlert(content)
                                    .setBuilderId(1).setTitle(content).build())
                    .addPlatformNotification(
                            IosNotification.newBuilder().setAlert(content)
                                    .autoBadge().setContentAvailable(true)
                                    .setSound("default").build()).build());
            PushPayload payload = builder.build();
            PushResult result = client.sendPush(payload);
            logger.debug("notice sended: " + new Date() + ",result: "
                    + result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 所有平台，推送目标是别名为 tag，通知内容为 content。
     *
     * @param client  the client
     * @param content the content
     * @param tags    the tags
     */
    public void pushWithTag(JPushClient client, String content, Set<String> tags) {
        try {
            PushPayload payload = PushPayload
                    .newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.tag(tags))
                    .setNotification(
                            Notification
                                    .newBuilder()
                                    .addPlatformNotification(
                                            AndroidNotification.newBuilder()
                                                    .setAlert(content)
                                                    .setBuilderId(1)
                                                    .setTitle(content).build())
                                    .addPlatformNotification(
                                            IosNotification.newBuilder()
                                                    .setAlert(content)
                                                    .autoBadge()
                                                    .setContentAvailable(true)
                                                    .setSound("default")
                                                    .build()).build()).build();
            PushResult result = client.sendPush(payload);
            logger.debug("notice sended: " + new Date() + ",result: "
                    + result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 所有平台，推送目标是别名为 alias，通知内容为 content。
     *
     * @param client  the client
     * @param content the content
     * @param alias   the alias
     */
    public void pushWithAlias(JPushClient client, String content,
                              String... alias) {
        if (alias == null || alias.length == 0 || alias[0] == null || StringUtils.isBlank(alias[0])) {
            this.logger.info("极光推送别名为空");
            return;
        }
        try {
            PushPayload payload = PushPayload
                    .newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.alias(alias))
                    .setNotification(
                            Notification
                                    .newBuilder()
                                    .addPlatformNotification(
                                            AndroidNotification.newBuilder()
                                                    .setAlert(content)
                                                    .setBuilderId(1)
                                                    .setTitle(MESSAGE_TITLE).build())
                                    .addPlatformNotification(
                                            IosNotification.newBuilder()
                                                    .setAlert(content)
                                                    .autoBadge()
                                                    .setContentAvailable(true)
                                                    .setSound("default")
                                                    .build()).build()).build();
            PushResult result = client.sendPush(payload);
            logger.info("notice sended: " + new Date() + ",result: "
                    + result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 
     * <p>推送自定义消息</p>
     * 
     * @param client
     * @param content
     * @param alias
     * @author: 虞云波 - yuyunbo@3856.cc 
     * @date: Created on 2017年12月6日 下午4:43:58
     */
    public void pushWithAliasByMessage(JPushClient client, JPushData data) {
    	Result resultFormat = new Result(Result.Status.OK, "请求成功", "200");
    	
				if (data == null || data.getAlias().size() == 0 || data.getAlias().get(0) == null || StringUtils.isBlank(data.getAlias().get(0))) {
				this.logger.info("极光推送别名为空");
				return;
				}
				resultFormat.setCode(data.getCode());
				resultFormat.setMessage(data.getContent());
				Message message = Message.newBuilder().setMsgContent(JSONUtil.getJSONString(resultFormat))  
			                .setTitle(MESSAGE_TITLE).build();  
				try {
				PushPayload payload = PushPayload
				  .newBuilder()
				  .setPlatform(Platform.all())
				  .setAudience(Audience.alias(data.getAlias()))
				  .setMessage(
						  message).build();
				PushResult result = client.sendPush(payload);
				logger.info("notice sended: " + new Date() + ",result: "
				  + result.toString());
				} catch (Exception e) {
				e.printStackTrace();
				}
	}

    /**
     * 所有平台，推送目标是别名为 alias，通知内容为 content。自定义消息
     *
     * @param client  the client
     * @param content the content
     * @param alias   the alias
     */
    public void pushWithAliasExt(JPushClient client, String content, Map<String, String> ext,
                                 String... alias) {
        if (alias == null || alias.length == 0 || alias[0] == null || StringUtils.isBlank(alias[0])) {
            this.logger.info("极光推送别名为空");
            return;
        }
        try {
            PushPayload payload = PushPayload
                    .newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.alias(alias))
                    .setNotification(
                            Notification
                                    .newBuilder()
                                    .addPlatformNotification(
                                            AndroidNotification.newBuilder()
                                                    .setAlert(content)
                                                    .setBuilderId(1)
                                                    .setTitle(content)
                                                    .addExtras(ext).build())
                                    .addPlatformNotification(
                                            IosNotification.newBuilder()
                                                    .setAlert(content)
                                                    .autoBadge()
                                                    .setContentAvailable(true)
                                                    .setSound("default")
                                                    .build()).build()).build();
            PushResult result = client.sendPush(payload);
            logger.info("notice sended: " + new Date() + ",result: "
                    + result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Push lbs message all.
     *
     * @param client  the client
     * @param content the content
     * @param lng     the lng
     * @param lat     the lat
     */
    public void pushLBSMessageAll(JPushClient client, String content, String lng, String lat) {
        try {
            PushPayload payload = PushPayload
                    .newBuilder()
                    .setPlatform(Platform.android_ios())
                    .setAudience(Audience.all())
                    .setOptions(Options.newBuilder().setTimeToLive(0L).build())
                    .setMessage(
                            Message.newBuilder().setMsgContent(content)
                                    .setTitle(MESSAGE_TITLE)
                                    .addExtra("lng", lng).addExtra("lat", lat)
                                    .build()).build();
            PushResult result = client.sendPush(payload);
            logger.debug("notice sended: " + new Date() + ",result: "
                    + result.toString());
            System.out.println("notice sended: " + new Date() + ",result: "
                    + result.toString());
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }

    /**
     * Push lbs message all with ex tra.
     *
     * @param client  the client
     * @param content the content
     * @param ext     the ext
     */
    public void pushLBSMessageAllWithExTra(JPushClient client, String content, Map<String, String> ext) {
        try {
            Builder builder = PushPayload.newBuilder();
            builder.setPlatform(Platform.android_ios());
            builder.setAudience(Audience.all());
            builder.setOptions(Options.newBuilder().setTimeToLive(0L).build());
            cn.jpush.api.push.model.Message.Builder mBuilder = Message.newBuilder();
            mBuilder.setMsgContent(content);
            mBuilder.setTitle(MESSAGE_TITLE);
            mBuilder.addExtras(ext);
            builder.setMessage(mBuilder.build());
            PushResult result = client.sendPush(builder.build());
            logger.debug("notice sended: " + new Date() + ",result: "
                    + result.toString());
            System.out.println("notice sended: " + new Date() + ",result: "
                    + result.toString());
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }

    /**
     * Push lbs message alias.
     *
     * @param client  the client
     * @param content the content
     * @param alias   the alias
     * @param lng     the lng
     * @param lat     the lat
     */
    public void pushLBSMessageAlias(JPushClient client, String content,
                                    String alias, String lng, String lat) {
        try {
            PushPayload payload = PushPayload
                    .newBuilder()
                    .setPlatform(Platform.android_ios())
                    .setAudience(Audience.alias(alias))
                    .setOptions(Options.newBuilder().setTimeToLive(0L).build())
                    .setMessage(
                            Message.newBuilder().setMsgContent(content)
                                    .setTitle(MESSAGE_TITLE)
                                    .addExtra("lng", lng).addExtra("lat", lat)
                                    .build()).build();
            PushResult result = client.sendPush(payload);
            logger.debug("notice sended: " + new Date() + ",result: "
                    + result.toString());
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }

    /**
     * Gets user client.
     *
     * @return the userClient
     */
    public JPushClient getUserClient() {
        if (userClient == null) {
            userClient = new JPushClient(userMastersecret, userAppkey);
        }
        return userClient;
    }

    /**
     * Sets user client.
     *
     * @param userClient the userClient to set
     */
    public void setUserClient(JPushClient userClient) {
        this.userClient = userClient;
    }

    /**
     * Gets user appkey.
     *
     * @return the userAppkey
     */
    public String getUserAppkey() {
        return userAppkey;
    }

    /**
     * Sets user appkey.
     *
     * @param userAppkey the userAppkey to set
     */
    public void setUserAppkey(String userAppkey) {

//		System.out.println("          \t            佛祖保佑       永无BUG                 ");
//		System.out.println("                           _ooOoo_                      ");
//		System.out.println("                          o8888888o                     ");
//		System.out.println("                          88\" . \"88                   ");
//		System.out.println("                          (| -_- |)                     ");
//		System.out.println("                          O\\  =  /O                    ");
//		System.out.println("                       ____/`---'\\____                 ");
//		System.out.println("                     .'  \\\\|     |//  `.              ");
//		System.out.println("                    /  \\\\|||  :  |||//  \\            ");
//		System.out.println("                   /  _||||| -:- |||||-  \\             ");
//		System.out.println("                   |   | \\\\\\  -  /// |   |           ");
//		System.out.println("                   | \\_|  ''\\---/''  |   |            ");
//		System.out.println("                   \\  .-\\__  `-`  ___/-. /            ");
//		System.out.println("                 ___`. .'  /--.--\\  `. . __            ");
//		System.out.println("              .\"\" '<  `.___\\_<|>_/___.'  >'\"\".     ");
//		System.out.println("             | | :  `- \\`.;`\\ _ /`;.`/ - ` : | |      ");
//		System.out.println("             \\  \\ `-.   \\_ __\\ /__ _/   .-` /  /    ");
//		System.out.println("        ======`-.____`-.___\\_____/___.-`____.-'======  ");
//		System.out.println("                           `=---='                      ");
//		System.out.println("        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^   ");
//		System.out.println();
//        System.out.println("jpush userAppkey:" + userAppkey);
        this.userAppkey = userAppkey;
    }

    /**
     * Gets user mastersecret.
     *
     * @return the userMastersecret
     */
    public String getUserMastersecret() {
        return userMastersecret;
    }

    /**
     * Sets user mastersecret.
     *
     * @param userMastersecret the userMastersecret to set
     */
    public void setUserMastersecret(String userMastersecret) {
        this.userMastersecret = userMastersecret;
    }
}
